package com.sjp.controller.admin;

import com.sjp.pojo.BlogCategory;
import com.sjp.service.CategoryService;
import com.sjp.util.Result;
import com.sjp.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @RequestMapping("/category")
    public String category(Model model){
        List<BlogCategory> blogCategories = categoryService.queryAllCategory();
        model.addAttribute("blogCategories",blogCategories);
        return "admin/category";
    }

    @PostMapping("/category/save")
    @ResponseBody
    public Result save(@RequestParam("name") String name) {
        if (StringUtils.isEmpty(name)) {
            return ResultGenerator.genFailResult("请输入分类名称！");
        }
        if (categoryService.saveCategory(name)) {
            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genFailResult("分类名称重复");
        }
    }

    @PostMapping("/category/delete")
    @ResponseBody
    public Result delete(@RequestParam("ids") Integer[] ids){
        if(categoryService.deleteCategory(ids) > 0){
            return ResultGenerator.genSuccessResult();
        }else{
            return ResultGenerator.genFailResult("删除失败！");
        }
    }

    @PostMapping("/category/update")
    @ResponseBody
    public Result update(@RequestParam("id") Integer id,@RequestParam("name") String name){
        if (StringUtils.isEmpty(name)) {
            return ResultGenerator.genFailResult("请输入修改后的分类名称！");
        }
        if(categoryService.updateCategory(id,name)){
            return ResultGenerator.genSuccessResult();
        }else{
            return ResultGenerator.genFailResult("修改失败！（是否该名字已存在呢）");
        }
    }
}
